package com.bookstore.back.controller;

import com.bookstore.back.common.Result;
import com.bookstore.back.service.MerchantService;
import com.bookstore.back.service.UserLogService;
import com.bookstore.back.util.UserContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 商家管理控制器
 * 
 * @author 程序猿_Ti
 * @since 2025-07-22
 */
@Slf4j
@RestController
@RequestMapping("/merchant")
public class MerchantController {

    @Autowired
    private MerchantService merchantService;

    @Autowired
    private UserLogService userLogService;

    @Autowired
    private UserContextUtil userContextUtil;

    // ==================== 业务统计相关 ====================
    
    /**
     * 获取商家业务统计数据
     */
    @GetMapping("/business/stats")
    public Result<Map<String, Object>> getBusinessStats() {
        try {
            Map<String, Object> stats = merchantService.getBusinessStats();
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取商家业务统计数据失败：{}", e.getMessage());
            return Result.error("获取业务统计数据失败");
        }
    }

    // ==================== 商家个人资料相关 ====================

    /**
     * 获取商家个人资料
     */
    @GetMapping("/profile")
    public Result<Map<String, Object>> getMerchantProfile() {
        try {
            Map<String, Object> profile = merchantService.getMerchantProfile();
            return Result.success(profile);
        } catch (Exception e) {
            log.error("获取商家个人资料失败：{}", e.getMessage());
            return Result.error("获取个人资料失败");
        }
    }

    /**
     * 更新商家个人资料
     */
    @PutMapping("/profile")
    public Result<String> updateMerchantProfile(@RequestBody Map<String, Object> profileData) {
        try {
            boolean success = merchantService.updateMerchantProfile(profileData);
            return success ? Result.success("个人资料更新成功") : Result.error("个人资料更新失败");
        } catch (Exception e) {
            log.error("更新商家个人资料失败：{}", e.getMessage());
            return Result.error("个人资料更新失败：" + e.getMessage());
        }
    }

    /**
     * 修改商家密码
     */
    @PutMapping("/password")
    public Result<String> changeMerchantPassword(@RequestBody Map<String, String> passwordData) {
        try {
            boolean success = merchantService.changeMerchantPassword(passwordData);
            return success ? Result.success("密码修改成功") : Result.error("密码修改失败");
        } catch (Exception e) {
            log.error("修改商家密码失败：{}", e.getMessage());
            return Result.error("密码修改失败：" + e.getMessage());
        }
    }

    /**
     * 获取商家统计信息
     */
    @GetMapping("/profile/stats")
    public Result<Map<String, Object>> getMerchantStats() {
        try {
            Map<String, Object> stats = merchantService.getMerchantStats();

            // 记录操作日志
            try {
                // 获取当前登录用户ID
                Long currentUserId = userContextUtil.getCurrentUserId();
                if (currentUserId != null) {
                    userLogService.recordOperationLog(currentUserId, "查看个人统计信息");
                }
            } catch (Exception logException) {
                log.warn("记录操作日志失败：{}", logException.getMessage());
            }

            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取商家统计信息失败：{}", e.getMessage());
            return Result.error("获取统计信息失败");
        }
    }

    /**
     * 上传商家头像
     */
    @PostMapping("/profile/avatar")
    public Result<Map<String, Object>> uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return Result.error("上传文件不能为空");
            }

            // 检查文件类型
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                return Result.error("文件名不能为空");
            }

            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
            if (!isValidImageExtension(fileExtension)) {
                return Result.error("只支持 jpg、jpeg、png、gif 格式的图片");
            }

            // 检查文件大小 (20MB)
            if (file.getSize() > 20 * 1024 * 1024) {
                return Result.error("文件大小不能超过 20MB");
            }

            // 创建上传目录
            String uploadDir = "uploads/avatar/" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 生成新的文件名
            String newFileName = UUID.randomUUID().toString() + fileExtension;
            Path filePath = uploadPath.resolve(newFileName);

            // 保存文件
            Files.copy(file.getInputStream(), filePath);

            // 构建返回的文件URL
            String fileUrl = "/" + uploadDir + "/" + newFileName;

            // 更新商家头像
            boolean updateSuccess = merchantService.updateMerchantAvatar(fileUrl);
            if (!updateSuccess) {
                return Result.error("更新头像失败");
            }

            Map<String, Object> result = new HashMap<>();
            result.put("url", fileUrl);
            result.put("originalName", originalFilename);
            result.put("size", file.getSize());

            log.info("商家头像上传成功：{}", fileUrl);
            return Result.success("头像上传成功", result);

        } catch (IOException e) {
            log.error("头像上传失败：{}", e.getMessage());
            return Result.error("头像上传失败：" + e.getMessage());
        } catch (Exception e) {
            log.error("头像上传异常：{}", e.getMessage());
            return Result.error("头像上传失败");
        }
    }

    /**
     * 检查图片文件扩展名是否有效
     */
    private boolean isValidImageExtension(String extension) {
        return extension.equals(".jpg") || extension.equals(".jpeg") ||
               extension.equals(".png") || extension.equals(".gif");
    }
}
